<template>
  <div v-if="cdata">
    <v-chart
      :forceFit="true"
      :height="height"
      :data="data"
      :scale="scale"
      :padding="[0, 120, 0, 0]"
    >
      <v-tooltip :showTitle="false" dataKey="item*percent" />
      <v-axis />
      <v-legend
        position="right-center"
        dataKey="item"
        :itemFormatter="format"
        :offsetX="40"
      />
      <v-pie
        position="percent"
        color="item"
        :vStyle="pieStyle"
        :label="false"
      />
      <v-coord type="theta" :radius="0.75" :innerRadius="0.6" />
    </v-chart>
  </div>
</template>

<script>
const DataSet = require("@antv/data-set");

export default {
  props: {
    cdata: {
      type: Object,
      default() {
        return null;
      }
    }
  },
  watch: {
    cdata: {
      immediate: true,
      deep: true,
      handler(cdata) {
        const sourceData = [
          { item: "青年", count: cdata[1] },
          { item: "中年", count: cdata[2] },
          { item: "老年", count: cdata[3] },
          { item: "少年", count: cdata[4] }
        ];

        const scale = [
          {
            dataKey: "percent",
            min: 0,
            formatter: ".0%"
          }
        ];

        const dv = new DataSet.View().source(sourceData);
        dv.transform({
          type: "percent",
          field: "count",
          dimension: "item",
          as: "percent"
        });
        const data = dv.rows;

        this.data = data;
        this.scale = scale;
      }
    }
  },
  data() {
    return {
      data: [],
      scale: [],
      height: (window.innerWidth / 1920) * 300,
      pieStyle: {
        stroke: "#1f2327",
        lineWidth: 1
      },
      labelConfig: [
        "percent",
        {
          formatter: (val, item) => {
            return item.point.item + ": " + val;
          },
          textStyle: {
            fill: "white",
            fontSize: 12,
            shadowBlur: 2,
            shadowColor: "rgba(0, 0, 0, .45)"
          }
        }
      ],
      format(val) {
        return val;
      }
    };
  }
};
</script>
